package org.edu.eece262.taskshare;

import java.util.ArrayList;
import java.util.LinkedList;

import org.edu.eece262.taskshare.ContactsDBAdapter.StatusType;
import org.edu.eece262.taskshare.Messages.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Contacts extends Activity {
	
	public static final String PREFS_NAME = "TASKSHARELOGIN";
	final CharSequence[] fields = {ContactsDBAdapter.KEY_USER_NAME, ContactsDBAdapter.KEY_NAME, ContactsDBAdapter.KEY_EMAIL, ContactsDBAdapter.KEY_PHONE};

	TabHost tabs;
	ListView lvContacts;
	SimpleCursorAdapter caContacts;
	ListView lvPendingContacts;
	SimpleCursorAdapter caPendingContacts;
	LinearLayout llPendingContacts;
	ListView lvRequests;
	SimpleCursorAdapter caRequests;
	Button bAdd;
	EditText etSearch;
	String query;
	LinkedList<User> llResults;
	ArrayList<String> llUsernames = new ArrayList<String>();
	boolean contactSelected;
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.contacts);
		
		final ContactsDBAdapter contactsDBA = ContactsDBAdapter.getContactsDBAdapter(getApplicationContext());
		contactsDBA.open();
		
		tabs = (TabHost)this.findViewById(R.id.tabhostContacts);
		tabs.setup();
		TabHost.TabSpec tab = tabs.newTabSpec("Contact Requests");
		tab.setContent(R.id.llRequests);
		tab.setIndicator("Requests", null);
		tabs.addTab(tab);
		tab = tabs.newTabSpec("Contacts");
		tab.setContent(R.id.llContacts);
		tab.setIndicator("Contacts", null);
		tabs.addTab(tab);
		tab = tabs.newTabSpec("Pending Requests");
		tab.setContent(R.id.llPending);
		tab.setIndicator("Pending", null);
		tabs.addTab(tab);
		tabs.setCurrentTab(0);
		
		lvContacts = (ListView) findViewById(R.id.lvContacts);
		caContacts = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_list_item_1, contactsDBA.getContacts(), 
				new String[] {ContactsDBAdapter.KEY_USER_NAME}, new int[] {android.R.id.text1});
		lvContacts.setAdapter(caContacts);
		lvContacts.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Cursor contacts = contactsDBA.getContacts();
				contacts.moveToPosition(arg2);
				viewContact(contacts.getString(ContactsDBAdapter.USER_NAME_COLUMN),
						contacts.getString(ContactsDBAdapter.NAME_COLUMN),
						contacts.getString(ContactsDBAdapter.PHONE_COLUMN),
						contacts.getString(ContactsDBAdapter.EMAIL_COLUMN));
				
			}
		});
		
		lvPendingContacts = (ListView) findViewById(R.id.lvPending);
		caPendingContacts = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_list_item_1, contactsDBA.getPendingContacts(), 
				new String[] {ContactsDBAdapter.KEY_USER_NAME}, new int[] {android.R.id.text1});
		lvPendingContacts.setAdapter(caPendingContacts);
		
		lvRequests = (ListView) findViewById(R.id.lvRequests);
		caRequests = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_list_item_1, contactsDBA.getContactRequests(), 
				new String[] {ContactsDBAdapter.KEY_USER_NAME}, new int[] {android.R.id.text1});
		lvRequests.setAdapter(caRequests);
		lvRequests.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Cursor requests = contactsDBA.getContactRequests();
				requests.moveToPosition(arg2);
				confirmUser(requests.getString(ContactsDBAdapter.USER_NAME_COLUMN),
						requests.getString(ContactsDBAdapter.NAME_COLUMN),
						requests.getString(ContactsDBAdapter.PHONE_COLUMN),
						requests.getString(ContactsDBAdapter.EMAIL_COLUMN));
			}
		});
		
		bAdd = (Button) findViewById(R.id.bSearchContacts);
		etSearch = (EditText) findViewById(R.id.etNewTask);
		
		bAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(0);
			}
		});
	}
	
	private void showUserList(final ArrayList<String> userNames, final LinkedList<User> users) {
		ListView lvResults = new ListView(this);
		final ArrayAdapter<String> aaContacts = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, userNames);
		lvResults.setAdapter(aaContacts);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Search Results").setSingleChoiceItems(aaContacts, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				contactSelected = false; 
				showUser(users.get(which), userNames, users);
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	private void showUser(final User user, final ArrayList<String> userNames, final LinkedList<User> users) {
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Add contact?")
		.setMessage("Name: " + user.getName() + "\nUsername: " + user.getUsername() + "\nEmail: " + user.getEmail() + "\nPhone: " + user.getPhonenumber())
		.setPositiveButton("Request", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				HTTPHelp.getActivityHTTPHelp().requestContact(user, getApplicationContext());
				contactSelected = true;
				notifyUpdate();
				dialog.dismiss();
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showUserList(userNames, users);
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	private void confirmUser(String username, String name, String phone, String email) {
		final User current = new Messages.User();
		current.setUsername(username);
		current.setName(name);
		current.setPhonenumber(phone);
		current.setEmail(email);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Add contact?")
		.setMessage("Name: " + name + "\nUsername: " + username + "\nEmail: " + email + "\nPhone: " + phone)
		.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				HTTPHelp.getActivityHTTPHelp().requestContact(current, getApplicationContext());
				ContactsDBAdapter contactsDBA = ContactsDBAdapter.getContactsDBAdapter(getApplicationContext());
				contactsDBA.open();
				Cursor localResults = contactsDBA.getEntriesMatching(current.getUsername());
				localResults.moveToFirst();
				while(!localResults.isAfterLast()) {
					contactsDBA.updateStatus(localResults.getInt(0), StatusType.ACTIVE);
					localResults.moveToNext();
				}
				contactsDBA.close();
				notifyUpdate();
				dialog.dismiss();
			}
		}).setNegativeButton("Reject", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				HTTPHelp.getActivityHTTPHelp().deleteContact(current, getApplicationContext());
				ContactsDBAdapter contactsDBA = ContactsDBAdapter.getContactsDBAdapter(getApplicationContext());
				contactsDBA.open();
				Cursor localResults = contactsDBA.getEntriesMatching(current.getUsername());
				localResults.moveToFirst();
				while(!localResults.isAfterLast()) {
					contactsDBA.removeEntry(localResults.getInt(0));
					localResults.moveToNext();
				}
				contactsDBA.close();
				notifyUpdate();
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	private void viewContact(String username, String name, String phone, String email) {
		final User current = new Messages.User();
		current.setUsername(username);
		current.setName(name);
		current.setPhonenumber(phone);
		current.setEmail(email);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Contact Details")
		.setMessage("Name: " + name + "\nUsername: " + username + "\nEmail: " + email + "\nPhone: " + phone)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	void notifyUpdate() {
		caContacts.notifyDataSetChanged();
		lvContacts.invalidate();
		caPendingContacts.notifyDataSetChanged();
		lvPendingContacts.invalidate();
		caRequests.notifyDataSetChanged();
		lvRequests.invalidate();
	}
	
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("Search by:")
		.setItems(fields, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		    	if (etSearch.getText().toString().length() < 3) {
					makeToast("Search must contain at least 3 characters.");
				} else {
						if (fields[item] == "Phone")
						{
							query = "PhoneNumber == '" + etSearch.getText().toString() + "'";
						} else {
							query = fields[item] + " == '" + etSearch.getText().toString() + "'";
						}
						// final LinkedList<User> llResults = HTTPHelp.getActivityHTTPHelp().searchUser(query, getApplicationContext().getSharedPreferences(PREFS_NAME, 0).getString("user", ""), getApplicationContext());
						final LinkedList<User> llResults = HTTPHelp.getActivityHTTPHelp().searchUser(query, getApplicationContext());
						ArrayList<String> llUsernames = new ArrayList<String>();
						for(int i = 0; i < llResults.size(); i++) {
							llUsernames.add(llResults.get(i).getUsername());
						}
						showUserList(llUsernames, llResults);
				}
		    }
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	void makeToast(String alert) {
		Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
				.show();
	}
}